from loguru import logger
from nonebot.adapters.cqhttp.bot import Bot
from nonebot.adapters.cqhttp.event import Event
from nonebot.permission import  USER, Permission
from nonebot.plugin import  on_notice
from nonebot.typing import T_State
from requests import get
import csv

from ...dao.class_student_dao import insert_class_student

from ...dao import group_dao
from ...utils.utils import get_options_list


async def _tea_id_checker(bot: Bot, event: Event, state: T_State) -> bool:
    # logger.opt(colors=True).info(f"名单：{event}")
    is_file = bool(event.notice_type == "offline_file")
    is_send_by_teacher = str(event.user_id) in bot.config.superusers
    return is_file and is_send_by_teacher


async def _permission_updater(
        bot: Bot, event: Event, state: T_State, permission: Permission) -> Permission:
    try:
        new_permission = USER(event.get_session_id(), perm=permission)
    except ValueError:
        new_permission = USER(str(event.user_id), perm=permission)
    return new_permission


import_stu_list = on_notice(rule=_tea_id_checker, priority=1, block=True)
import_stu_list._default_permission_updater = _permission_updater


@import_stu_list.handle()
async def import_stu_list_handler(bot: Bot, event: Event, state: T_State):
    if not str(event.file["name"]).endswith(".csv"):
        await import_stu_list.finish("请发送csv格式的学生名单！")
    state["file"] = event.file
    cls_list = await group_dao.getAllClass(bot)
    cls_options = get_options_list(list(map(lambda x: x.name, cls_list)))
    state["cls_list"] = cls_list
    state["class_count"] = len(cls_list)
    await import_stu_list.send(cls_options)
    await import_stu_list.send("你想导入哪个班级的名单呢？")


@import_stu_list.receive()
async def handle_class(bot: Bot, event: Event, state: T_State):
    state["class_no"] = str(event.get_message()).strip()
    logger.info(event)
    try:
        num = int(state["class_no"])
    except ValueError:
        await import_stu_list.reject("请输入数字！")

    if num < 0 or state["class_count"] <= num:
        await import_stu_list.reject("请输入在{}到{}之间的数字！".format(0, state["class_count"] - 1))


@import_stu_list.handle()
async def handle_stu_list(bot: Bot, event: Event, state: T_State):
    file: dict = state["file"]
    gid = state["cls_list"][int(state["class_no"])].gid
    stu_list = get(file['url'], allow_redirects=True)
    with open(f"static/{file['name']}", 'wb') as f:
        f.write(stu_list.content)
    with open(f"static/{file['name']}") as f:
        stu_list_reader = csv.reader(f)
        for row in stu_list_reader:
            if row[0].isdigit():
                await insert_class_student(gid,row[0])
            else:
                await import_stu_list.finish("学生名单格式错误！")
    await import_stu_list.finish("学生名单导入成功！")
            
        
